import React, { useState } from 'react'
import { Input, AutoComplete } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { SelectProps } from 'antd'

export interface MenuSearchProps {
  menuItems: any[]
  onMenuSelect: (path: string) => void
}

const MenuSearch: React.FC<MenuSearchProps> = ({ menuItems, onMenuSelect }) => {
  const [searchText, setSearchText] = useState('')
  const [searchResults, setSearchResults] = useState<SelectProps['options']>([])

  // 处理菜单搜索
  const handleSearch = (value: string) => {
    setSearchText(value)
    if (value) {
      // 递归展平菜单项以便搜索
      const flattenMenuItems = (items: any[]): any[] => {
        let result: any[] = []
        items.forEach(item => {
          result.push(item)
          if (item.children) {
            result = result.concat(flattenMenuItems(item.children))
          }
        })
        return result
      }

      const flattenedItems = flattenMenuItems(menuItems)
      
      // 搜索匹配项
      const results = flattenedItems
        .filter(item => item.label && item.label.toLowerCase().includes(value.toLowerCase()))
        .map(item => ({
          value: item.path,
          label: item.label
        }))
      
      setSearchResults(results)
    } else {
      setSearchResults([])
    }
  }

  // 处理搜索选择
  const handleSelect = (value: string) => {
    onMenuSelect(value)
    setSearchText('')
    setSearchResults([])
  }

  return (
    <div style={{ padding: '16px 16px 0 16px' }}>
      <AutoComplete
        style={{ width: '100%' }}
        options={searchResults}
        onSelect={handleSelect}
        onSearch={handleSearch}
        value={searchText}
        placeholder="搜索菜单..."
      >
        <Input suffix={<SearchOutlined />} />
      </AutoComplete>
    </div>
  )
}

export default MenuSearch